import { useState } from 'react'

interface KeyMap {
  [key: string]: any
}

type Value = {
  path: string,
  key: string,
  value: any
}

interface StoreItem {
  value: any,
  dispatch: Array<any>
}

interface Store {
  [key: string]: StoreItem
}

const isInitStore: KeyMap = {}
const store: Store = {}

function _setValue(key: string, value: any) {
  store[key].value = value
  store[key].dispatch.forEach((cb: any) => {
    cb(value)
  })
}

// like subscribe
export function useSbuscribe(option: Value) {
  const {path, key, value} = option  
  const [state, setState] = useState(value)

  // 如果没有被初始化，则初始化一次
  if (!isInitStore[key]) {
    store[key] = { value: value, dispatch: [] }
    isInitStore[key] = { value: true }
  }

  if (!isInitStore[key][path]) {
    store[key].dispatch = [...store[key].dispatch, setState]
    isInitStore[key][path] = true
  }

  return [state, (_value: any) => _setValue(key, _value)]
}

export function useDispatch(key: string) {
  return (value: any) => _setValue(key, value)
}

